// MethodTemplateForm/SharedComponents/ResourceArrayEditor.jsx
import React from "react";
import { Plus, Trash2 } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";

const ResourceArrayEditor = ({ title, items = [], onUpdate }) => {
  // 处理添加资源（生成唯一ID）
  const handleAddResource = () => {
    // 转换现有资源为带ID格式（兼容旧数据）
    const resourcesWithIds = items.map((item) => 
      item.id ? item : { ...item, id: Date.now().toString() + Math.random().toString(36).substr(2, 5) }
    );
    // 添加新资源（带唯一ID）
    const newResource = {
      id: Date.now().toString() + Math.random().toString(36).substr(2, 5),
      name: "",
      specification: "",
      quantity: 1,
      unit: ""
    };
    onUpdate([...resourcesWithIds, newResource]);
  };

  // 处理资源字段更新
  const handleUpdateResource = (index, field, value) => {
    const updatedResources = [...items];
    // 确保资源项有ID（兼容旧数据）
    if (!updatedResources[index].id) {
      updatedResources[index].id = Date.now().toString() + Math.random().toString(36).substr(2, 5);
    }
    // 特殊处理数字类型字段
    updatedResources[index][field] = field === 'quantity' ? Number(value) || 1 : value;
    onUpdate(updatedResources);
  };

  // 处理资源删除
  const handleRemoveResource = (index) => {
    onUpdate(items.filter((_, i) => i !== index));
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <h4 className="font-medium">{title}</h4>
        <Button variant="outline" size="sm" onClick={handleAddResource}>
          <Plus className="w-4 h-4 mr-2" /> 添加
        </Button>
      </div>
      <div className="space-y-3">
        {items.map((resource, index) => (
          // 使用资源项的id作为key（确保稳定性）
          <div key={resource.id || `${index}-${Date.now()}`} className="grid grid-cols-12 gap-2 items-center p-2 border rounded-lg bg-white">
            <div className="col-span-12 sm:col-span-4">
              <Label className="text-xs text-gray-500">名称</Label>
              <Input
                value={resource.name || ""}
                onChange={(e) => handleUpdateResource(index, "name", e.target.value)}
                placeholder="资源名称"
              />
            </div>
            <div className="col-span-12 sm:col-span-3">
              <Label className="text-xs text-gray-500">规格型号</Label>
              <Input
                value={resource.specification || ""}
                onChange={(e) => handleUpdateResource(index, "specification", e.target.value)}
                placeholder="规格型号"
              />
            </div>
            <div className="col-span-6 sm:col-span-2">
              <Label className="text-xs text-gray-500">数量</Label>
              <Input
                type="number"
                min="1"
                value={resource.quantity || 1}
                onChange={(e) => handleUpdateResource(index, "quantity", e.target.value)}
              />
            </div>
            <div className="col-span-6 sm:col-span-2">
              <Label className="text-xs text-gray-500">单位</Label>
              <Input
                value={resource.unit || ""}
                onChange={(e) => handleUpdateResource(index, "unit", e.target.value)}
                placeholder="单位"
              />
            </div>
            <div className="col-span-12 sm:col-span-1 flex justify-end">
              <Button
                variant="ghost"
                size="icon"
                onClick={() => handleRemoveResource(index)}
                className="text-red-500 hover:text-red-700"
              >
                <Trash2 className="w-4 h-4" />
              </Button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default ResourceArrayEditor;